package JasPerl::PSGI;

use strict;
use warnings;

use Module::Load;

use JasPerl::PageConfig;

use JasPerl::PSGI::Request;
#use JasPerl::PSGI::RequestDispatcher;

sub new {
    my $class = shift;
    bless { attributes => { } }, $class;
}

sub new_request {
    my ($class, $env) = @_;
    return JasPerl::PSGI::Request->new($env);
}

sub get_request_dispatcher {
    my ($self, $path) = @_;
    # TODO: check if plain file, use right file dispatcher
    # TODO: cache dispatchers
    # FIXME: exception handling

    my $module = get_module_name($path);

    load $module;

    my $page = $module->new;
    $page->init(JasPerl::PageConfig->new($module, $self));
    warn "## $page $path";
    return JasPerl::RequestDispatcher->new($page, $path);
}

sub get_attribute_names {
    return JasPerl::Util::Enumeration->from_list(keys %{$_[0]->{attributes}});
}

sub get_attribute {
    return $_[0]->{attributes}->{$_[1]};
}

sub set_attribute {
    if (defined $_[2]) {
        $_[0]->{attributes}->{$_[1]} = $_[2];
    } else {
        delete $_[0]->{attributes}->{$_[1]};
    }
}

sub remove_attribute {
    delete $_[0]->{attributes}->{$_[1]};
}

sub get_module_name {
    # FIXME: from context?
    my $jsp_package = 'Local::JSP';

    my $path = shift;
    my @pseg = map {
        s/(\W|_)+/_/g;
        length($_) ? ($_) : ()
    } split('/', $path);
    unshift @pseg, $jsp_package if $jsp_package;
    return join('::', @pseg);
}

1;
